package com.carp.controller;

import com.carp.common.DBResult;
import com.carp.entity.CarpArticle;
import com.carp.service.CarpArticleService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ArticleController {
    @Resource
    private CarpArticleService carpArticleService;

    //查询我的文章
    @PostMapping("/selectArticle")
    public DBResult toSelect(@RequestParam(value = "uid") Integer uid){
        List<CarpArticle> carpArticles = carpArticleService.selectMyArticle(uid);
        if (carpArticles.isEmpty()){
            return DBResult.error(500,"查询为空!");
        }
        return DBResult.success(carpArticles);
    }


    //发布文章(添加)
    @PostMapping("/addArticle")
    public DBResult toAddArticle(@RequestBody CarpArticle carpArticle){
        System.out.println(carpArticle);
        Boolean aBoolean = carpArticleService.insertArticle(carpArticle);
        if (aBoolean){
            return DBResult.success("插入成功!");
        }
        return DBResult.error();
    }

    //修改文章
    @PostMapping("/updateArticle")
    public DBResult toUpdateArticle(@RequestBody CarpArticle carpArticle){
        Boolean aBoolean = carpArticleService.editArticle(carpArticle);
        if (aBoolean){
            return DBResult.success("修改成功!");
        }
        return DBResult.error();
    }

    //逻辑删除文章
    @PostMapping("/deleteArticle")
    public DBResult toDeleteArticle(@RequestParam(value = ("id")) Long id){
        Boolean aBoolean = carpArticleService.deleteArticle(id);
        if (aBoolean){
            return DBResult.success("删除成功!");
        }
        return DBResult.error();
    }

    //分页
    @PostMapping("/page")
    public DBResult toPage(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                           @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize,
                           @RequestParam("uid") Integer uid){
        //当前用户的所有文章总数
        int size = carpArticleService.selectMyArticle(uid).size();

        //获取分页后的数据
        List<CarpArticle> pagination = carpArticleService.pagination(pageNum, pageSize,uid);

        HashMap<String, Object> map = new HashMap<>();
        //一页的数据
        map.put("onePageList",pagination);
        //查询的总数数据条数
        map.put("pageList",size);

        return DBResult.success(map);
    }
}
